//
//  HandeARViewController.m
//  HandeAR
//
//  Created by HandeIdealVision on 2017/10/30.
//  Copyright © 2017年 HandeIdealVison. All rights reserved.
//

#import "HandeARViewController.h"
#import "HandeAR+Private.h"
#import "UnityAppController.h"
#import <AVFoundation/AVFoundation.h>

extern NSNotificationName finishInitUnit;

@interface HandeARViewController ()
@property (nonatomic, strong) UIColor *originNavigationBarTintColor;
@property (nonatomic, strong) UIImage *originNavigationBarBackgroundImage;
@property (nonatomic, strong) UIImage *originNavigationBarShadowImage;
@property (nonatomic, assign) BOOL originNavigationBarTranslucent;

@property (nonatomic, weak) UIView *arView;

@property (nonatomic, weak) UIView *arLoadView;
@property (nonatomic, weak) UILabel *arLoadingLabel;
@end

@implementation HandeARViewController


- (void)viewDidLoad {
    [super viewDidLoad];
//    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
    self.view.backgroundColor = [UIColor blackColor];
    // Do any additional setup after loading the view.
    [UIView setAnimationsEnabled:YES];
    
    NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"HandeAR" withExtension:@"bundle"]];
    NSString *imagePath = [bundle pathForResource:@"back" ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setBackgroundImage:image forState:UIControlStateNormal];
    [backBtn setBackgroundImage:image forState:UIControlStateHighlighted];
    [backBtn setBackgroundImage:image forState:UIControlStateSelected];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(25, 25, 40, 40);
    [self.view addSubview:backBtn];
    
//    UIButton *pauseBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//    [pauseBtn setTitle:@"Pause" forState:UIControlStateNormal];
//    pauseBtn.frame = CGRectMake(25, 100, 100, 44);
//    [pauseBtn addTarget:self action:@selector(pauseAudio) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:pauseBtn];
//
//    UIButton *resumeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//    [resumeBtn setTitle:@"Resume" forState:UIControlStateNormal];
//    resumeBtn.frame = CGRectMake(25, 150, 100, 44);
//    [resumeBtn addTarget:self action:@selector(resumeAudio) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:resumeBtn];
    
//    HandeARView *arView = [[HandeARView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    self.arView = arView;
//    [self.view addSubview:self.arView];
//    [self.view sendSubviewToBack:self.arView];
    
    
}

- (void)rotateView:(UIImageView *)view  fx: (BOOL)isN {
    CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    if (isN) {
        rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI*2.0];
    }
    else {
        
        rotationAnimation.toValue = [NSNumber numberWithFloat:-M_PI*2.0];
    }
    rotationAnimation.duration = 1;
    rotationAnimation.repeatCount = HUGE_VALF;
    [view.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

- (void)finishLoadingUnity {
    self.arLoadingLabel.hidden = YES;
    self.arLoadView.hidden = YES;
}

- (void)pauseAudio {
    [[HandeAR sharedInstance] pauseAudio];
}

- (void)resumeAudio {
    [[HandeAR sharedInstance] unPauseAudio];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
    //UIStatusBarStyleDefault = 0 黑色文字，浅色背景时使用
    //UIStatusBarStyleLightContent = 1 白色文字，深色背景时使用
}

- (BOOL)prefersStatusBarHidden
{
    return YES; //返回NO表示要显示，返回YES将hiden
}

- (void)loadView {
    [super loadView];
    UIView *view = UnityGetGLView();
    if (view) {
        [self.view addSubview:view];
        self.arView = view;
    }
    [self applicationDidBecomeActive:nil];
    [[HandeAR sharedInstance] initUnity];
    
    CGRect screenBounds = [UIScreen mainScreen].bounds;
    CGFloat screenWidth = CGRectGetWidth(screenBounds);
    CGFloat screenHeight = CGRectGetHeight(screenBounds);
    CGFloat width = 128;
    CGFloat height = 128;
    UIView *arLoadView = [[UIView alloc] initWithFrame:CGRectMake((screenWidth - width) / 2.0, (screenHeight - height) / 2.0, width, height)];
    [self.view addSubview:arLoadView];
    self.arLoadView = arLoadView;
    self.arLoadView.clipsToBounds = YES;
    
    int scale = [UIScreen mainScreen].scale;
    UIImage *img1 = [self imagesNamedFromCustomBundle:[NSString stringWithFormat:@"001@%dx", scale]];
    UIImage *img2 = [self imagesNamedFromCustomBundle:[NSString stringWithFormat:@"002@%dx", scale]];
    UIImageView *imgV1 = [[UIImageView alloc] initWithImage:img1];
    UIImageView *imgV2 = [[UIImageView alloc] initWithImage:img2];
    imgV1.frame = CGRectMake(0, 0, width, height);
    imgV2.frame = CGRectMake(0, 0, width, height);
    [self.arLoadView addSubview:imgV1 ];
    [self.arLoadView addSubview:imgV2 ];
    [self rotateView:imgV1 fx:YES];
    [self rotateView:imgV2 fx:NO];
    
    UILabel *arLoadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(arLoadView.frame) + 10, screenWidth, 30)];
    arLoadingLabel.backgroundColor = [UIColor clearColor];
    arLoadingLabel.textColor = [UIColor whiteColor];
    arLoadingLabel.textAlignment = NSTextAlignmentCenter;
    arLoadingLabel.font = [UIFont systemFontOfSize:15];
    arLoadingLabel.text = @"AR加载中...";
    [self.view addSubview:arLoadingLabel];
    self.arLoadingLabel = arLoadingLabel;
}

- (UIImage *)imagesNamedFromCustomBundle:(NSString *)imgName {
    NSString *bundlePath = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"HandeAR.bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    NSString *img_path = [bundle pathForResource:imgName ofType:@"png"];
    return [UIImage imageWithContentsOfFile:img_path];
}

- (id)init {
    self = [super init];
    if (self) {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
        [center addObserver:self selector:@selector(finishLoadingUnity) name:finishInitUnit object:nil];
    }
    
    return self;
}

- (void)refreshPreview {
    NSArray *subviews = self.view.subviews;
    for (UIView *v in subviews) {
        [v removeFromSuperview];
    }
    UIView *view = UnityGetGLView();
    if (view) {
        [self.view addSubview:view];
    }
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
//    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
//    self.navigationItem.leftBarButtonItem = item;
    
    self.originNavigationBarTintColor = self.navigationController.navigationBar.tintColor;
    self.originNavigationBarBackgroundImage = [self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsDefault];
    self.originNavigationBarShadowImage = [self.navigationController.navigationBar shadowImage];
    self.originNavigationBarTranslucent = self.navigationController.navigationBar.translucent;
    
    
//    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
//    [self.navigationController.navigationBar setBackgroundImage: [UIImage new] forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
//    self.navigationController.navigationBar.translucent = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [[HandeAR sharedInstance] clearUnity];

    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationController.navigationBar setTintColor:self.originNavigationBarTintColor];
    [self.navigationController.navigationBar setBackgroundImage: self.originNavigationBarBackgroundImage forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:self.originNavigationBarShadowImage];
    self.navigationController.navigationBar.translucent = self.originNavigationBarTranslucent;
}

- (void)dealloc {
    [[HandeAR sharedInstance] clearUnity];
//    UnityAppController *unityController = (UnityAppController*)[[HandeAR sharedInstance] valueForKey:@"unityController"];
//    [unityController applicationWillResignActive:[UIApplication sharedApplication]];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center removeObserver:self];
}

- (void)applicationDidBecomeActive:(NSNotification *)notice {
    UnityAppController *unityController = (UnityAppController*)[[HandeAR sharedInstance] valueForKey:@"unityController"];
    [unityController applicationDidBecomeActive:[UIApplication sharedApplication]];
}

- (void)cancel {
    if (self.presentingViewController) {
        if (self.navigationController.viewControllers[0] == self) {
            [self dismissViewControllerAnimated:YES completion:nil];
            
            return;
        }
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
